package org.iartisan.wechatsdk.miniprogram

import org.iartisan.runtime.utils.HttpRequestUtil
import org.iartisan.wechatsdk.Utils._
import org.iartisan.wechatsdk.common.WechatErrcode
import org.iartisan.wechatsdk.common.res.WechatResError
import org.iartisan.wechatsdk.miniprogram.req.WxTemplateMsgReq
import org.iartisan.wechatsdk.{LogAspect, WechatGsonBuilder}

/**
  * 模板消息
  *
  * @author King  2019-8-20
  */
object TemplateMsgService extends LogAspect {

  private val url_template_send = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s"

  def send(req: WxTemplateMsgReq): Unit = {
    val accessToken = MiniappAccessToken.getAccessToken
    req.setAccessToken(accessToken)
    val url = String.format(url_template_send, accessToken)
    try {
      val data = WechatGsonBuilder.create.toJson(req)
      log.info("{}[{}] 请求 {}", LOG_REQ, "TemplateMsgService.send", data)
      val response = HttpRequestUtil.sendPost(url, data)
      val body = response.body.string
      log.info("{}[{}] 返回 {}", LOG_RES, "TemplateMsgService.send", body)
      val wechatResError = body.toObject[WechatResError]

      if (wechatResError.getErrcode != 0)
        if (wechatResError.getErrcode == WechatErrcode.E_40001.id) {
          //刷新token 重新调用接口
          log.info("{}[{}] {}", LOG_RES, "TemplateMsgService.send", "token过期，重刷token后再调用")
          MiniappAccessToken.refreshAccessToken
          send(req)
        }
        else throw new RuntimeException(wechatResError.getErrmsg)
    } catch {
      case e: Exception =>
        throw new RuntimeException(e.getMessage)
    }
  }
}
